import { fitChartSize } from '../utils/tools';
import { worldGeoCoordMap } from './coorDataSimple';
import { emptyIcon, offIcon, onIcon, tipBg } from './mapIcon';
import { fetchStationLocation } from './useFetchStationData';

export const worldMapConfig = async (configData: any) => {
  let { data, toolTipData, chinaCount, intl } = configData;
  // 统计在线和离线站点数量
  let onlineCount: number = 0;
  let offlineCount: number = 0;
  toolTipData.forEach((item: any) => {
    if (item.online) {
      onlineCount++;
    } else {
      offlineCount++;
    }
  });
  const stationData = await fetchStationLocation();
  // 定义中国区域的经纬度范围
  const isInChina = (longitude: number, latitude: number) => {
    return longitude >= 73 && longitude <= 135 && latitude >= 3.5 && latitude <= 54;
  };
  // toolTipData = toolTipData.filter(
  //   (item: { stationName: string | string[] }) => !item.stationName.includes('平安夜'),
  // );
  stationData.forEach((station) => {
    const { stationLongitude, stationLatitude, stationAddress } = station;
    // 如果站点不在中国区域，则加入到 worldGeoCoordMap 中
    if (!isInChina(stationLongitude, stationLatitude)) {
      worldGeoCoordMap[stationAddress] = [stationLongitude, stationLatitude];
      console.log('worldGeoCoordMap---', worldGeoCoordMap);
    }
  });

  const convertData = (data: any[]) => {
    const res = [];
    for (let i = 0; i < data.length; i++) {
      const geoCoord = worldGeoCoordMap[data[i].name];
      if (geoCoord) {
        res.push({
          name: data[i].name,
          value: geoCoord.concat(data[i].online ? 1 : 0), // 使用 1 表示在线，0 表示离线
          online: data[i].online,
        });
      }
    }
    return res;
  };
  const highlightChinaData = (chinaCount: number) => {
    const uniqueNames = new Set(); // 用于记录已添加的名称，防止重复添加
    return toolTipData
      .map((item: { name: string | number; online: any; count?: number }) => {
        if (uniqueNames.has(item.name)) {
          return null;
        }
        uniqueNames.add(item.name);
        const geoCoord = worldGeoCoordMap[item.name];
        if (geoCoord) {
          return {
            name: item.name,
            value: geoCoord.concat(item.online ? 1 : 0), // 使用 1 表示在线，0 表示离线
            online: item.online,
            symbol: item.name === '中国' ? emptyIcon : item.online ? onIcon : offIcon,
            symbolSize:
              item.name === '中国'
                ? [fitChartSize(42), fitChartSize(48)]
                : [fitChartSize(42), fitChartSize(48)],
            symbolOffset: [0, -20],
            itemStyle: {
              normal: {
                color: item.online ? '#feb40e' : '#3ebbff',
                shadowBlur: false,
                shadowColor: false,
              },
              opacity: 1,
            },
            label: {
              normal: {
                show: item.name === '中国',
                formatter: item.name === '中国' ? `{b|${chinaCount}}` : '',
                position: 'inside',
                textStyle: {
                  color: '#fff',
                  fontSize: fitChartSize(14),
                  fontWeight: 'normal',
                  backgroundColor: 'transparent',
                },
                rich: {
                  b: {
                    fontSize: fitChartSize(14),
                    color: '#fff',
                    fontWeight: 'bold',
                  },
                },
              },
            },
            rippleEffect: {
              color: item.online ? '#feb40e' : '#3ebbff',
            },
          };
        } else {
          console.warn(`Geo coordinates not found for ${item.name}`);
          return null;
        }
      })
      .filter((item: null) => item !== null);
  };

  return {
    backgroundColor: 'transparent',
    title: {
      show: false,
      text: '项目分布图',
      x: 'center',
      top: '10',
      textStyle: {
        color: '#fff',
        fontFamily: '等线',
        fontSize: 18,
      },
    },
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove',
      alwaysShowContent: false,
      backgroundColor: 'transparent',
      borderWidth: 0,
      padding: 0,
      formatter: function (params: { name: string }) {
        if (params.name === '中国') {
          return '';
        }
        let toolTiphtml = '';
        for (let i = 0; i < toolTipData.length; i++) {
          if (params.name === toolTipData[i].name) {
            toolTiphtml = `<div style="width:240px;height:240px;background:url(${tipBg});background-size:100% 100%;overflow:hidden;" class="bgTip">
              <div style="width:100%;height:20px;line-height:40px;padding:0 20px">
                <i style="display:inline-block;width:8px;height:8px;border-radius:40px;"></i>
                <span style="margin-left:10px;color:#fff;font-size:16px;"></span>
              </div>
              <div style="padding:0px 20px">
                <p style="color:#73E7FB;font-size:14px;line-height: 18px; margin-bottom:10px;max-width: 170px; text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">
                ${toolTipData[i].stationName}</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.operationTime',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].date
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 15px; margin-bottom: 5px; display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.tenantName',
                })}:<span style="display:block;color:#C4D4F1;margin-left:3px;font-size:12px; max-width: 130px; text-overflow: ellipsis;white-space: nowrap;overflow: hidden;">${
              toolTipData[i].tenant
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.ratedCapacity',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].capacity
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.ratedPower',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].power
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.zEfficiency',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].efficiency
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.cycleIndex',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].loop
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.integratedEfficiency',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].all
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.totalC',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].charge
            }</span></p>
                <p style="color:#C4D4F1;font-size:12px;line-height: 14px; margin-bottom: 5px;display: flex; align-itmes: center;">
                ${intl.formatMessage({
                  id: 'bigdata.totalDc',
                })}:<span style="color:#C4D4F1;margin-left:3px;font-size:12px;">${
              toolTipData[i].discharge
            }</span></p>
              </div>
            </div>`;
            break;
          }
        }
        return toolTiphtml;
      },
      show: true,
    },
    visualMap: {
      show: true,
      type: 'piecewise',
      pieces: [
        {
          value: 1,
          label: `${intl.formatMessage({ id: 'bigdata.online' })} (${onlineCount})`,
          color: '#feb40e',
        },
        {
          value: 0,
          label: `${intl.formatMessage({ id: 'bigdata.offline' })} (${
            offlineCount > 0 ? offlineCount - 1 : offlineCount
          })`,
          color: '#3ebbff',
        },
      ],
      textStyle: {
        color: '#508FFF',
        fontSize: 12,
      },
      left: 0,
      bottom: 80,
      itemWidth: 20,
      itemHeight: 12,
    },
    geo: [
      {
        layoutCenter: ['50%', '50%'],
        layoutSize: '120%',
        show: true,
        map: 'world',
        roam: true,
        zoom: 1.2,
        aspectScale: 0.75,
        center: undefined,
        groupId: 'world-map-group', // 添加 groupId
        label: {
          normal: {
            show: false,
            textStyle: {
              color: '#fff',
            },
          },
          emphasis: {
            show: true,
            textStyle: {
              color: '#fff',
            },
          },
        },
        itemStyle: {
          normal: {
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true,
            },
            borderColor: 'rgba(192, 243, 251,0.5)',
            borderWidth: 1,
            shadowOffsetY: 15,
            shadowBlur: 12,
            // shadowColor: 'rgba(58,149,253,1)',
          },
          emphasis: {
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true,
            },
          },
        },
      },
    ],
    series: [
      {
        type: 'map',
        map: 'world',
        geoIndex: 0,
        aspectScale: 1,
        zoom: 1,
        showLegendSymbol: true,
        roam: true,
        groupId: 'world-map-group', // 添加 groupId
        label: {
          normal: {
            show: true,
            textStyle: {
              color: '#fff',
              fontSize: '120%',
            },
          },
        },
        itemStyle: {
          show: false,
          normal: {
            areaColor: {
              type: 'linear',
              x: 1200,
              y: 0,
              x2: 0,
              y2: 0,
              colorStops: [
                {
                  offset: 0,
                  color: 'rgba(3,27,78,0.75)',
                },
                {
                  offset: 1,
                  color: 'rgba(58,149,253,0.75)',
                },
              ],
              global: true,
            },
            borderColor: '#fff',
            borderWidth: 0.2,
          },
        },
        layoutCenter: ['50%', '50%'],
        layoutSize: '180%',
        animation: false,
        markPoint: {
          symbol: 'none',
        },
        data: data,
      },
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        geoIndex: 0,
        zlevel: 5,
        label: {
          normal: {
            show: false,
            formatter: function (params: { data: { name: any; value: any[] } }) {
              let name = params.data.name;
              let value = params.data.value[2];
              let text = `{tline|${name}} : {fline|${value}}个`;
              return text;
            },
            color: '#fff',
            rich: {
              fline: {
                color: '#fff',
                fontSize: 14,
                fontWeight: 600,
              },
              tline: {
                color: '#ABF8FF',
                fontSize: 12,
              },
            },
          },
          emphasis: {
            show: false,
          },
        },
        symbolSize: [32, 37],
        symbolOffset: [0, -20],
        data: highlightChinaData(chinaCount),
        itemStyle: {
          normal: {
            opacity: function (params: { data: { value: number[] } }) {
              return params.data.value[2] === 1 ? 1 : 0; // 根据在线状态设置透明度
            },
          },
        },
      },
      {
        name: 'Top 5',
        type: 'effectScatter',
        coordinateSystem: 'geo',
        data: convertData(toolTipData),
        showEffectOn: 'render',
        groupId: 'world-map-group', // 添加 groupId
        rippleEffect: {
          scale: 5,
          brushType: 'stroke',
        },
        label: {
          normal: {
            formatter: '{b}',
            position: 'bottom',
            show: false,
            color: '#fff',
            distance: 10,
          },
        },
        symbol: 'circle',
        symbolSize: [20, 10],
        itemStyle: {
          normal: {
            color: function (params: { data: { online: boolean } }) {
              return params.data.online ? '#feb40e' : '#3ebbff';
            },
            shadowBlur: 10,
            shadowColor: function (params: { data: { online: boolean } }) {
              return params.data.online ? '#feb40e' : '#3ebbff';
            },
          },
          opacity: 1,
        },
        zlevel: 4,
      },
    ],
  };
};
